# -*- coding: utf-8 -*-
"""
@File    :   common.py
@Time    :   2024/04/12 16:00:10
@Author  :   Ennis.Zhou 
@Desc    :   None
"""
from flask import session, g, request, jsonify
from authlib.jose import jwt
from werkzeug.utils import secure_filename as wku_secure_filename
from unicodedata import normalize
from config import BaseConfig
from functools import wraps

from utils.response_code import RET


def create_token(user_id, **kwargs):
    """
    生成token
    :return: token
    """
    header = {"alg": "HS256"}
    data = {"id": user_id}
    data.update(**kwargs)
    token = None
    try:
        token = jwt.encode(header=header, payload=data, key=BaseConfig.SECRET_KEY)
        token = bytes.decode(token)
    except Exception as e:
        raise e
    return token


def verify_token(token):
    """
    校验token
    :param token:
    :return: true 或 false
    """
    try:
        # 转换为字典
        data = jwt.decode(token, BaseConfig.SECRET_KEY)
    except Exception as e:
        raise e
    return data


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        user_id = session.get("uuid")
        print("userid-------", user_id)
        try:
            token_data = verify_token(request.headers["token"])
        except Exception as e:
            raise e
        token_id = token_data["id"]
        user = None
        if (user_id and token_id) and (user_id == token_id):
            try:
                from apps.models.user import User

                user = User.query.get(user_id)
            except Exception as e:
                raise e
        g.user = user
        if g.user is None:
            return jsonify(code=RET.DBERR, msg="登录信息不存在")
        return func(*args, **kwargs)

    return wrapper


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in BaseConfig.ALLOWED_EXTENSIONS


def secure_filename(filename: str, target_ext: str = None) -> str:
    """
    扩展的安全文件名处理函数，支持中文。
    将非ASCII字符转换为其合法的字符表示。
    """
    # 使用Werkzeug的原生secure_filename函数处理基本的安全性问题
    filename = wku_secure_filename(filename)

    # 对中文等非ASCII字符进行转码处理
    filename = normalize('NFKD', filename).encode('IDNA').decode('utf-8')

    # 如果提供了目标扩展名，确保文件名有该扩展名
    if target_ext:
        filename = filename.rsplit('.', maxsplit=1)[0] + '.' + target_ext

    return filename



